import { Controller } from 'egg';

const VALIDATE_LOGIN = {
    weixin_code: {
        type: 'string',
        required: true,
        allowEmpty: false,
    },
    avatar: {
        type: 'string',
        required: false,
        allowEmpty: true,
    },
};

export default class LoginController extends Controller {
    public async login() {
        const { ctx, service } = this;
        ctx.validate(VALIDATE_LOGIN);

        const { weixin_code, avatar } = ctx.request.body;
        const openid = await this.service.weixin.getOpenid(weixin_code);
        if (!openid) {
            this.ctx.helper.innerError('微信登录过期');
        }
        const result = await service.login.loginByOpenID(openid, avatar);
        ctx.helper.success(ctx, result);
    }
}
